import styles from './index.module.less';

import { useEffect, useState } from 'react';
import axios from 'axios';
import { Editor, IParts } from '@lle/d3-editor';

import { fetchParts } from '@/api/parts';
import { IPart } from '@/types';
import { convertLocalUrl } from '@/utils/FileUtils';

interface IProps {
  editor?: Editor;
  plHangNo?: string;
}

export const PartList = (props: IProps) => {
  const { plHangNo, editor } = props;
  const [parts, setParts] = useState<IPart[]>([]);

  useEffect(() => {
    const getData = async (plHangNo: string) => {
      const response = await fetchParts(plHangNo);

      const headers = {
        Authorization:
          'Basic yoLW40nmQqrlJsmeFwRR7dNPQ14C6IVhVgGID8QzxP6GdJcQIliTbVy00Szcu7l5QNHr5dLkQ/bPuF8w79G/cdNZ_r5yU0jl2kkYFpbVR8A=',
      };

      const promises = [];
      for (let i = 0; i < response.data.length; i++) {
        const element = response.data[i];
        promises.push(
          axios.get(convertLocalUrl(element.thumbnaiUrl), { headers, responseType: 'arraybuffer' })
        );
      }

      const results = await Promise.all(promises);

      for (let i = 0; i < results.length; i++) {
        const element = results[i];

        const blob = new Blob([element.data]);

        response.data[i].thumbnaiUrl = URL.createObjectURL(blob);
      }

      for (let i = 0; i < response.data.length; i++) {
        const element = response.data[i];
        element.extra = element.applyNum === 0; // 属于可选零件列表
      }

      editor?.partsManager.setParts(response.data);
    };
    if (plHangNo && editor) {
      getData(plHangNo);
    }
  }, [plHangNo, editor]);

  useEffect(() => {
    const updateParts = (parts: IParts[]) => setParts([...parts]);

    editor?.bus.on('PARTS_UPDATED', updateParts);

    return () => {
      editor?.bus.off('PARTS_UPDATED', updateParts);
    };
  }, [editor]);

  const onDragItem = (event: React.DragEvent, item: IPart) => {
    const data = { type: 'part', item };
    event.dataTransfer.setData('text', JSON.stringify(data));
  };

  return (
    <div className={styles.container}>
      <div className={styles.top}>
        <div className={styles.title}>当前挂组零件列表</div>
        <div className={styles.partContainer}>
          {parts
            .filter(item => item.extra)
            .map(item => (
              <div key={item.id} className={styles.part} onDragStart={e => onDragItem(e, item)}>
                <img
                  src={item.thumbnaiUrl}
                  crossOrigin="anonymous"
                  alt="图片"
                  className={styles.icon}
                />
                <div className={styles.font}>{item.foNo}</div>
                <div className={styles.font}>{item.fpartNo}</div>
                <div>{item.name}</div>
                <div>
                  {item.applyNum} / {item.total}
                </div>
              </div>
            ))}
        </div>
      </div>
      <div className={styles.top}>
        <div className={styles.title}>可选零件列表</div>
        <div className={styles.partContainer}>
          {parts
            .filter(item => !item.extra)
            .map(item => (
              <div key={item.id} className={styles.part} onDragStart={e => onDragItem(e, item)}>
                <img
                  src={item.thumbnaiUrl}
                  crossOrigin="anonymous"
                  alt="图片"
                  className={styles.icon}
                />
                <div className={styles.font}>{item.foNo}</div>
                <div className={styles.font}>{item.fpartNo}</div>
                <div>{item.name}</div>
                <div>
                  {item.applyNum} / {item.total}
                </div>
              </div>
            ))}
        </div>
      </div>
    </div>
  );
};
